//
//  AppDelegate.m
//  classroom
//
//  Created by Macx on 16/7/30.
//  Copyright © 2016年 LiuZhuo. All rights reserved.
//

#import "AppDelegate.h"
#import "CSHomeTableViewController.h"
#import "CSTabBarController.h"
#import "Reachability.h"
#import "UMSocial.h"
#import "UMSocialSinaSSOHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialDataService.h"

@interface AppDelegate ()
@property(nonatomic,strong)Reachability * internetReachability;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch. 57b1c38167e58ebbf40033f9
    
#pragma mark - 集成友盟
    //设置友盟社会化组件appkey
    [UMSocialData setAppKey:@"57b1c38167e58ebbf40033f9"];
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"http://www.umeng.com/social"];
    //设置手机QQ 的AppId，Appkey，和分享URL，需要#import "UMSocialQQHandler.h"
    [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"http://www.umeng.com/social"];
    //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。需要 #import "UMSocialSinaSSOHandler.h"
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3921700954"
                                              secret:@"04b48b094faeb16683c32669824ebdad"
                                         RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    
#pragma mark - 获取用户授权
    UIUserNotificationType  type =   UIUserNotificationTypeNone | UIUserNotificationTypeBadge | UIUserNotificationTypeSound |    UIUserNotificationTypeAlert ;
    UIUserNotificationSettings * settings = [ UIUserNotificationSettings settingsForTypes:type categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#pragma mark - 添加伐木工
    // Standard lumberjack initialization
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    // And we also enable colors
    [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
    
#pragma mark - 设置根控制器
    UIWindow * win = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    win.backgroundColor = [UIColor whiteColor];
    self.window = win;
    [self.window makeKeyAndVisible];
    self.window.rootViewController = [[CSTabBarController alloc]init];
#pragma mark - 判断网络状态
    
    //添加一个系统通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    //初始化
    self.internetReachability=[Reachability reachabilityForInternetConnection];
    
    //通知添加到Run Loop
    [self.internetReachability startNotifier];
    
    [self updateInterfaceWithReachability:_internetReachability];
    
    return YES;

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * ison = [userDefaults objectForKey:@"推送"];
    if ([ison isEqualToString:@"关"]) {
        return ;
    }
    
    
    
    NSDate *testDate = [NSDate date];

    //to set the fire date
     DDLogDebug(@"%@-=-=-=-",testDate);
    NSCalendar *calender = [NSCalendar autoupdatingCurrentCalendar]; // 取得当前系统日历的值
    NSDateComponents *dateComponents = [calender components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour fromDate:testDate];
    DDLogDebug(@"%ld-=-=-",(long)dateComponents.hour);
    if (dateComponents.hour < 8 ) {
        [dateComponents setHour:8];
    }else{
        [dateComponents setHour:32];
    }
    
    NSDate *fireDate = [calender dateFromComponents:dateComponents];

    //1.创建本地通知  特定的时间显示出来 (定制)
    UILocalNotification *local = [[UILocalNotification alloc]init];
    //2.初始化  属性
    local.alertBody = @"今日教室占用情况已更新，点击查看";
    local.alertAction = @"查看";
    //    local.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
//        local.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    DDLogDebug(@"%@-=-=-=-=",fireDate);
    local.fireDate = fireDate;

    
    local.applicationIconBadgeNumber =0;
    local.category = @"hello";
    local.userInfo = @{@"name" : @"刘卓" };
    
    //3.定制  使用
    [[UIApplication sharedApplication]scheduleLocalNotification:local];
    
    
    
    UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc]init];
    
    //唯一标示
    category.identifier = @"hello";
    UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc]init];
    action1.identifier = @"111";
    action1.title = @"立即查看";
    action1.activationMode = UIUserNotificationActivationModeForeground;
    action1.authenticationRequired = NO;
    action1.destructive = NO;
    
    
    UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc]init];
    action2.identifier = @"222";
    action2.title = @"稍后再说";
    action2.activationMode = UIUserNotificationActivationModeBackground;
    action2.authenticationRequired = NO;
    action2.destructive = YES;
    
    //UIUserNotificationActionContextDefault 默认可以添加四个动作
    [category setActions:@[action1,action2] forContext:UIUserNotificationActionContextDefault];
    
    NSSet *set = [NSSet setWithObjects:category, nil];
    
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert  categories:set];
    
    [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
    
    
    

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NetworkStatus netStatus = [reachability currentReachabilityStatus];
      NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    switch (netStatus) {
        case NotReachable:
            DDLogDebug(@"====当前网络状态不可用=======");
            [userDefaults setBool:0 forKey:@"网络状态为3G"];
            [userDefaults synchronize];
            break;
        case ReachableViaWiFi:
            DDLogDebug(@"====当前网络状态为Wifi=======");
            [userDefaults setBool:0 forKey:@"网络状态为3G"];
            [userDefaults synchronize];
            break;
        case ReachableViaWWAN:
            DDLogDebug(@"====当前网络状态为3G=======");
          
            [userDefaults setBool:1 forKey:@"网络状态为3G"];
            [userDefaults synchronize];
            break;
    }
}

@end
